package com.mlog.njyjy.ndop.monitor.cfg;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

@WebFilter(urlPatterns = "/*")
@Configuration
@Order(1)
public class InvokeFilter implements Filter {

	private static final Log log = LogFactory.get();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		long t = System.currentTimeMillis();
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String url = request.getRequestURI().toString();
		String method = request.getMethod();
		Map<String, String[]> m = servletRequest.getParameterMap();
		List<String> params = new ArrayList<>();
		for (String key : m.keySet()) {
			params.add(key + ":" + servletRequest.getParameter(key));
		}
//		log.warn(String.format("\n[%s] ==>> URI:[%s], Params:%s", method, url, params));
		filterChain.doFilter(servletRequest, servletResponse);
		log.warn("\n[{}] ==>> URI:[{}], Params:{}, cost:[{}]ms", method, url, params,
				System.currentTimeMillis() - t);
	}

	@Override
	public void destroy() {

	}
}
